package leetCode;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * TODO
 *
 * @author 司松坡
 * @createTime 2023年02月27日
 */
public class LeetCode18 {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        //数组长度
        int length = nums.length;
        //先排序
        Arrays.sort(nums);
        //初始化最大值
        int max = nums[nums.length - 1];
        //初始化返回值
        List<List<Integer>> rs = new ArrayList<>();
        if (length < 4) {
            return rs;
        }
        //循环遍历
        for (int i = 0; i < length - 3; i++) {
            if ((long)target - nums[i] > (long)max * 3) {
                continue;
            }
            if ((long)target - nums[i] < (long)nums[i] * 3) {
                break;
            }
            if ((long)nums[i] * 4 > target) {
                return rs;
            }
            for (int j = i + 1; j < length - 2; j++) {
                if ((long)target - nums[i] - nums[j] > (long)max * 2) {
                    continue;
                }
                if ((long)target - nums[i] - nums[j] < (long)nums[j] * 2) {
                    break;
                }
                for (int k = j + 1; k < length - 1; k++) {
                    if ((long)target - nums[i] - nums[j] - nums[k] > max) {
                        continue;
                    }
                    if ((long)target - nums[i] - nums[j] - nums[k]< nums[k]) {
                        break;
                    }
                    for (int l = k +1 ;l<length ;l++){
                        if ((long)target - nums[i] - nums[j] - nums[k]> max) {
                            continue;
                        }
                        if ((long)target - nums[i] - nums[j] - nums[k]< nums[l]) {
                            break;
                        }
                        if ((long)target - nums[i] - nums[j] - nums[k] - nums[l]== 0){
                            List<Integer> list = new ArrayList<>();
                            list.add(nums[i]);
                            list.add(nums[j]);
                            list.add(nums[k]);
                            list.add(nums[l]);
                            if (!rs.contains(list)){
                                rs.add(list);
                            }
                        }
                    }
                }
            }
        }
        return rs;
    }


    @Test
    public void test(){
        int[] nums = {0,0,0,-1000000000,-1000000000,-1000000000,-1000000000};
        System.out.println(fourSum(nums,-1000000000));
    }

}
